package com.cardbaobao.cardbabyclient.ui.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cardbaobao.cardbabyclient.R;
import com.cardbaobao.cardbabyclient.api.Api;
import com.cardbaobao.cardbabyclient.buried.Google;
import com.cardbaobao.cardbabyclient.buried.Self;
import com.cardbaobao.cardbabyclient.buried.SelfUtils;
import com.cardbaobao.cardbabyclient.ui.activity.AccountLoginActivity;
import com.cardbaobao.cardbabyclient.ui.activity.CardDoProgressActivity;
import com.cardbaobao.cardbabyclient.ui.activity.CreditRepaymentActivity;
import com.cardbaobao.cardbabyclient.ui.activity.DailyRedEnvelopesActivity;
import com.cardbaobao.cardbabyclient.ui.activity.FindBankActivity;
import com.cardbaobao.cardbabyclient.ui.activity.HotActivitiesActivity;
import com.cardbaobao.cardbabyclient.ui.activity.base.BaseActivity;
import com.cardbaobao.cardbabyclient.ui.activity.web.EventWebViewActivity;
import com.cardbaobao.cardbabyclient.ui.adapter.DiscoverBusinessAdapter;
import com.cardbaobao.cardbabyclient.base.Constant;
import com.cardbaobao.cardbabyclient.callback.RecycleItemClickedCallback;
import com.cardbaobao.cardbabyclient.controller.CommonJumpController;
import com.cardbaobao.cardbabyclient.ui.activity.CreditToMoneyActivity;
import com.cardbaobao.cardbabyclient.ui.fragment.base.BaseFragment;
import com.cardbaobao.cardbabyclient.ui.activity.AcademicInquiryActivity;
import com.cardbaobao.cardbabyclient.ui.activity.InquiriesActivity;
import com.cardbaobao.cardbabyclient.ui.activity.InquiriesFailureActivity;
import com.cardbaobao.cardbabyclient.ui.activity.InquiriesSuccessActivity;
import com.cardbaobao.cardbabyclient.ui.activity.ProvidentFundResultActivity;
import com.cardbaobao.cardbabyclient.ui.activity.SocialSecurityResultActivity;
import com.cardbaobao.cardbabyclient.model.Banner;
import com.cardbaobao.cardbabyclient.model.Event;
import com.cardbaobao.cardbabyclient.model.ImageResAndText;
import com.cardbaobao.cardbabyclient.model.QueryStateModel;
import com.cardbaobao.cardbabyclient.model.result.BannerResult;
import com.cardbaobao.cardbabyclient.utils.ApplicationHelper;
import com.cardbaobao.cardbabyclient.utils.DensityUtil;
import com.cardbaobao.cardbabyclient.buried.GoogleAnalyticsUtil;
import com.cardbaobao.cardbabyclient.utils.ImageLoaderUtil;
import com.cardbaobao.cardbabyclient.utils.JsonUtil;
import com.cardbaobao.cardbabyclient.utils.ScreenUtil;
import com.cardbaobao.cardbabyclient.utils.ToastUtil;
import com.cardbaobao.cardbabyclient.utils.URLUtil;
import com.cardbaobao.cardbabyclient.utils.UmengEventUtils;
import com.cardbaobao.cardbabyclient.utils.ViewUtil;
import com.cardbaobao.cardbabyclient.widget.divider.GridDividerItemDecoration;
import com.stx.xhb.xbanner.XBanner;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import rx.Observable;
import rx.Subscriber;


/**
 * 发现
 * Created by zad
 * 2016/8/1 9:18
 */

public class DiscoverFragment extends BaseFragment {
    private String prePageId;
    public void setBuriedInfo(String prePageId){
        this.prePageId=prePageId;
    }
    @BindView(R.id.xb_banner)
    XBanner xBanner;

    @BindView(R.id.recycler_view)
    RecyclerView recyclerView;

    private Class<?> toActivity = null;

    private int queryType = -1;//查询类型 0社保、1公积金

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_discover;
    }

    /**
     * 控件初始化
     *
     * @param view
     * @param savedInstanceState
     */
    @Override
    protected void initViewFinish(View view, Bundle savedInstanceState) {
        EventBus.getDefault().register(this);
        initIntent();

        mCurrentPageId= Self.Page.app_discovery_index_page;

        //计算viewPager高度 宽高比750/390
        ViewGroup.LayoutParams params = xBanner.getLayoutParams();
        params.height = (int) ((ScreenUtil.getScreenWidth(getContext().getApplicationContext()) * 39) / 75.0f);
        xBanner.setLayoutParams(params);
        xBanner.setmAutoPalyTime(Constant.BANNER_INTERVAL_TIME);

        initGridView();
        loadBannerData();
    }

    @OnClick({R.id.rl_popular_activities, R.id.rl_daily_red_envelopes})
    public void onClick(View view) {
        initIntent();
        mIntent.putExtra(BaseActivity.PRE_PAGE_ID_S,mCurrentPageId);
        switch (view.getId()) {
            case R.id.rl_popular_activities:
                //热门活动
                SelfUtils.buriedClickData(Self.Action.app_click_discovery_hot_event,
                        Self.Action.app_click_discovery_hot_event_des,
                        mEnterPageTime,
                        mCurrentPageId,
                        prePageId);
                mIntent.setClass(mContext, HotActivitiesActivity.class);
                startActivity(mIntent);
                break;
            case R.id.rl_daily_red_envelopes:
                //每日红包
                SelfUtils.buriedClickData(Self.Action.app_click_discovery_daily_red_envelope,
                        Self.Action.app_click_discovery_daily_red_envelope_des,
                        mEnterPageTime,
                        mCurrentPageId,
                        prePageId);
                mIntent.setClass(mContext, DailyRedEnvelopesActivity.class);
                startActivity(mIntent);
                break;
        }
    }

    private void loadBannerData() {
        Observable<String> observable = Api.getBannerData(Constant.GLB0312);
        observable.subscribe(new Subscriber<String>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                ToastUtil.showToast(ApplicationHelper.
                        getApplicationContext().
                        getString(R.string.string_request_server_fail));
            }

            @Override
            public void onNext(String s) {
                BannerResult bannerResult = JsonUtil.json2Object(s, BannerResult.class);
                if (bannerResult.getCode() == Constant.SUC_CODE) {
                    if (bannerResult.getData() != null) {
                        xBanner.stopAutoPlay();
                        final List<Banner.CarouselFigureListBean> data =
                                bannerResult.getData().getCarousel_figure_list();
                        xBanner.setData(data, null);
                        xBanner.setmAdapter(new XBanner.XBannerAdapter() {
                            @Override
                            public void loadBanner(XBanner banner, Object model, View view, int position) {
                                ImageLoaderUtil.displayImage(URLUtil.CBB_IMG_URL + ((Banner.CarouselFigureListBean) model).getImage(),
                                        (ImageView) view);
                            }
                        });
                        xBanner.setOnItemClickListener(new XBanner.OnItemClickListener() {
                            @Override
                            public void onItemClick(XBanner banner, int position) {
                                SelfUtils.buriedClickData(Self.Action.app_click_discovery_top_banner,
                                        Self.Action.app_click_discovery_top_banner_des,
                                        mEnterPageTime,
                                        mCurrentPageId,
                                        prePageId);
                                CommonJumpController controller = new CommonJumpController(mContext);
                                Banner.CarouselFigureListBean bean = data.get(position);
                                Map<String, Object> extra = new HashMap<>();
                                extra.put(CommonJumpController.FROM_PAGE, "发现-banner");
                                extra.put(EventWebViewActivity.WEB_TYPE_I, 34);
                                controller.bannerJump(bean, extra);
                            }
                        });
                        xBanner.startAutoPlay();
                    }
                } else {
                    ToastUtil.showToast(bannerResult.getMsg());
                }
            }
        });
    }

    private void initGridView() {
        final List<ImageResAndText> data = new ArrayList<>();
        data.add(new ImageResAndText(R.mipmap.icon_card_progress_01, "办卡进度"));
        data.add(new ImageResAndText(R.mipmap.icon_to_money, "信用变钱"));
        data.add(new ImageResAndText(R.mipmap.icon_near_bank, "附近银行"));
        data.add(new ImageResAndText(R.mipmap.icon_social_security_inquiries, "社保查询"));
        data.add(new ImageResAndText(R.mipmap.icon_provident_fund_inquiries, "公积金查询"));
        data.add(new ImageResAndText(R.mipmap.icon_academic_inquiries, "学历查询"));
        data.add(new ImageResAndText(R.mipmap.icon_find_repayment, "信用卡还款"));
        GridLayoutManager manager = new GridLayoutManager(mContext, 2, GridLayoutManager.VERTICAL, false);
        manager.setSmoothScrollbarEnabled(true);
        ViewUtil.configRecycleViewInScrollView(recyclerView, manager);
        int padding26 = DensityUtil.dp2px(13.0f);
        GridDividerItemDecoration itemDecoration =
                new GridDividerItemDecoration(padding26, 0);
        recyclerView.addItemDecoration(itemDecoration);
        DiscoverBusinessAdapter adapter = new DiscoverBusinessAdapter(mContext);
        adapter.setData(data);
        adapter.setClickedCallback(new RecycleItemClickedCallback() {
            @Override
            public void onRecycleItemClicked(int position) {
                ImageResAndText item = data.get(position);
                GoogleAnalyticsUtil.setScreenAction(Google.CAREGORY_ORD, "发现-" + item.getText());
                mIntent.putExtra(BaseActivity.PRE_PAGE_ID_S,mCurrentPageId);
                switch (item.getText()) {
                    case "信用变钱":
                        SelfUtils.buriedClickData(Self.Action.app_click_discovery_credit_to_money,
                                Self.Action.app_click_discovery_credit_to_money_des,
                                mEnterPageTime,
                                mCurrentPageId,
                                prePageId);
                        if (mApplication.getIsLogin()) {
                            mIntent.setClass(mContext, CreditToMoneyActivity.class);
                            startActivity(mIntent);
                        } else {
                            toActivity = CreditToMoneyActivity.class;
                            toLoginActivity(Constant.PLY010207);
                        }
                        break;
                    case "办卡进度":
                        SelfUtils.buriedClickData(Self.Action.app_click_discovery_card_progress,
                                Self.Action.app_click_discovery_card_progress_des,
                                mEnterPageTime,
                                mCurrentPageId,
                                prePageId);
                        mIntent.setClass(mContext, CardDoProgressActivity.class);
                        startActivity(mIntent);
                        break;
                    case "附近银行":
                        SelfUtils.buriedClickData(Self.Action.app_click_discovery_near_by_bank,
                                Self.Action.app_click_discovery_near_by_bank_des,
                                mEnterPageTime,
                                mCurrentPageId,
                                prePageId);
                        mIntent.setClass(mContext, FindBankActivity.class);
                        mIntent.putExtra(BaseActivity.PRE_PAGE_ID_S,mCurrentPageId);
                        startActivity(mIntent);
                        break;
                    case "社保查询":
                        SelfUtils.buriedClickData(Self.Action.app_click_discovery_social_security_inquiry,
                                Self.Action.app_click_discovery_social_security_inquiry_des,
                                mEnterPageTime,
                                mCurrentPageId,
                                prePageId);
                        if (mApplication.getIsLogin()) {
                            Map<String, String> sMap = new HashMap<>();
                            sMap.put("userId", String.valueOf(mApplication.getUser().getID()));
                            UmengEventUtils.clickEvent(mContext,
                                    ApplicationHelper.getApplicationContext().getString(R.string.event_0x041),
                                    sMap);
                            loadQueryInfo(0);
                        } else {
                            queryType = 0;
                            toLoginActivity(Constant.PLY010208);
                        }
                        break;
                    case "公积金查询":
                        SelfUtils.buriedClickData(Self.Action.app_click_discovery_provident_fund_inquiry,
                                Self.Action.app_click_discovery_provident_fund_inquiry_des,
                                mEnterPageTime,
                                mCurrentPageId,
                                prePageId);
                        if (mApplication.getIsLogin()) {
                            Map<String, String> gMap = new HashMap<>();
                            gMap.put("userId", String.valueOf(mApplication.getUser().getID()));
                            UmengEventUtils.clickEvent(mContext,
                                    ApplicationHelper.getApplicationContext().getString(R.string.event_0x042),
                                    gMap);
                            loadQueryInfo(1);
                        } else {
                            queryType = 1;
                            toLoginActivity(Constant.PLY010209);
                        }
                        break;
                    case "学历查询":
                        SelfUtils.buriedClickData(Self.Action.app_click_discovery_education_history_inquiry,
                                Self.Action.app_click_discovery_education_history_inquiry_des,
                                mEnterPageTime,
                                mCurrentPageId,
                                prePageId);
                        if (mApplication.getIsLogin()) {
                            Map<String, String> aMap = new HashMap<>();
                            aMap.put("userId", String.valueOf(mApplication.getUser().getID()));
                            UmengEventUtils.clickEvent(mContext,
                                    ApplicationHelper.getApplicationContext().getString(R.string.event_0x043),
                                    aMap);
                            mIntent.setClass(mContext, AcademicInquiryActivity.class);
                            mIntent.putExtra(BaseActivity.PRE_PAGE_ID_S,mCurrentPageId);
                            startActivity(mIntent);
                        } else {
                            toActivity = AcademicInquiryActivity.class;
                            toLoginActivity(Constant.PLY010210);
                        }
                        break;
                    case "信用卡还款":
                        SelfUtils.buriedClickData(Self.Action.app_click_discovery_credit_card_repayment,
                                Self.Action.app_click_discovery_credit_card_repayment_des,
                                mEnterPageTime,
                                mCurrentPageId,
                                prePageId);
                        if (mApplication.getIsLogin()) {
                            Intent upperQuota = new Intent(mContext, CreditRepaymentActivity.class);
                            upperQuota.putExtra(BaseActivity.PRE_PAGE_ID_S,mCurrentPageId);
                            startActivity(upperQuota);
                        } else {
                            toLoginActivity(Constant.PLY010211);
                        }
                        break;
                }
            }
        });
        recyclerView.setAdapter(adapter);
    }

    private void toLoginActivity(String loginRequestFrom) {
        mIntent.setClass(mContext, AccountLoginActivity.class);
        mIntent.putExtra(AccountLoginActivity.JUM_TYPE_I, 3);
        mIntent.putExtra(AccountLoginActivity.LOGIN_REQUEST_FROM_S,
                loginRequestFrom);
        startActivity(mIntent);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }


    /**
     * 获取查询社保、公积金信息
     *
     * @param type 0社保 1公积金
     */
    private void loadQueryInfo(final int type) {
        showProgressDialog(true);
        Observable<String> observable =
                Api.socialFundQueryResult(mApplication.getUser().getID());
        observable.subscribe(new Subscriber<String>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                dismissProgressDialog();
                ToastUtil.showToast(ApplicationHelper.
                        getApplicationContext().
                        getString(R.string.string_request_data_fail));
            }

            @Override
            public void onNext(String s) {
                dismissProgressDialog();
                JSONArray array = JSON.parseArray(s);
                if (array != null) {
                    JSONObject object;
                    QueryStateModel gjj = null;
                    QueryStateModel sheBao = null;
                    for (int i = 0, size = array.size(); i < size; i++) {
                        object = array.getJSONObject(i);
                        if ("GJJ".equals(object.getString("channel_type"))) {
                            gjj = new QueryStateModel("GJJ", object.getIntValue("state"));
                        } else if ("SHE_BAO".equals(object.getString("channel_type"))) {
                            sheBao = new QueryStateModel("SHE_BAO", object.getIntValue("state"));
                        }
                    }
                    if (type == 0) {
                        //社保
                        mIntent.putExtra("channel_type", "SHE_BAO");
                        if (sheBao == null) {
                            mIntent.setClass(mContext, InquiriesActivity.class);
                        } else {
                            int state = sheBao.getState();
                            if (state == 0) {
                                mIntent.setClass(mContext, InquiriesSuccessActivity.class);
                            } else if (state == 1) {
                                //查询成功
                                mIntent.setClass(mContext, SocialSecurityResultActivity.class);
                            } else {
                                //查询失败
                                mIntent.setClass(mContext, InquiriesFailureActivity.class);
                            }
                        }
                        mIntent.putExtra(BaseActivity.PRE_PAGE_ID_S,mCurrentPageId);
                        startActivity(mIntent);
                    } else if (type == 1) {
                        //公积金
                        mIntent.putExtra("channel_type", "GJJ");
                        if (gjj == null) {
                            mIntent.setClass(mContext, InquiriesActivity.class);
                        } else {
                            int state = gjj.getState();
                            if (state == 0) {
                                mIntent.setClass(mContext, InquiriesSuccessActivity.class);
                            } else if (state == 1) {
                                //查询成功
                                mIntent.setClass(mContext, ProvidentFundResultActivity.class);
                            } else {
                                //查询失败
                                mIntent.setClass(mContext, InquiriesFailureActivity.class);
                            }
                        }
                        mIntent.putExtra(BaseActivity.PRE_PAGE_ID_S,mCurrentPageId);
                        startActivity(mIntent);
                    }
                }
            }
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(Event.LoginSucNotify loginSucNotify) {
        if (loginSucNotify.getType() == 3) {
            if (toActivity != null) {
                mIntent.setClass(mContext, toActivity);
                startActivity(mIntent);
                toActivity = null;
            } else {
                loadQueryInfo(queryType);
            }
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (xBanner != null) {
            if (isVisible()) {
                xBanner.startAutoPlay();
            } else {
                xBanner.stopAutoPlay();
            }
        }
        if (!hidden) {
            GoogleAnalyticsUtil.setScreenName(Google.NEW_DISCOVER);
        }
    }

}
